<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter"
      :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-form-item label="标题" prop="title">
              <el-input v-model="queryParams.title" placeholder="请输入标题" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="需求类型" prop="requireType">
              <el-select v-model="queryParams.requireType" placeholder="请选择需求类型" clearable>
                <el-option v-for="dict in pm_require_type" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="优先级" prop="priority">
              <el-select v-model="queryParams.priority" placeholder="请选择优先级" clearable>
                <el-option v-for="dict in pm_priorities" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="负责人" prop="owner">
              <el-select v-model="queryParams.owner" filterable placeholder="请选择" clearable>
                <el-option v-for="([key, value], index) in Object.entries(postOptions)" :key="key" :label="value"
                           :value="key" @keyup.enter="handleQuery">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="关联人员" prop="relatedUsers">
              <el-select v-model="queryParams.relatedUsers" filterable placeholder="请选择" clearable>
                <el-option v-for="([key, value], index) in Object.entries(postOptions)" :key="key" :label="value"
                           :value="key" @keyup.enter="handleQuery">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="状态">
              <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>
                <el-option v-for="dict in pm_require_status" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAdd"
              v-hasPermi="['pm:require:add']">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()"
              v-hasPermi="['pm:require:edit']">修改</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()"
              v-hasPermi="['pm:require:remove']">删除</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="warning" plain icon="Download" @click="handleExport"
              v-hasPermi="['pm:require:export']">导出</el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList" :columns="columns"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" :data="requireList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="需求主键" align="center" prop="id" v-if="false" />
        <!-- <el-table-column label="租户编号" align="center" prop="tenantId" /> -->
        <el-table-column v-if="columns[0].visible" label="标题" align="center" prop="title" :show-overflow-tooltip="true" width="300">
          <template #default="scope">
            <router-link :to="'/pm/require-data/index/' + scope.row.id" class="link-type">
              <span>{{ scope.row.title }}</span>
            </router-link>
          </template>
        </el-table-column>
        <el-table-column v-if="columns[1].visible" label="需求类型" align="center" prop="requireType">
          <template #default="scope">
            <dict-tag :options="pm_require_type" :value="scope.row.requireType" />
          </template>
        </el-table-column>
        <el-table-column v-if="columns[2].visible" label="优先级" align="center" prop="priority">
          <template #default="scope">
            <dict-tag :options="pm_priorities" :value="scope.row.priority" />
          </template>
        </el-table-column>
        <el-table-column v-if="columns[3].visible" label="内容" align="center" prop="content"
          :show-overflow-tooltip="true" />
        <!-- <el-table-column label="图片、文件" align="center" prop="files" /> -->
        <el-table-column v-if="columns[4].visible" label="关联客户" align="center" prop="tenantId">
          <template #default="scope">
            <el-tag v-for="([key, value]) in filteredRequireList(clientList, scope.row.tenantId)">{{ value }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column v-if="columns[5].visible" label="关联人员" align="center" prop="relatedUsers"  width="300">
          <template #default="scope">
            <el-tag v-for="([key, value]) in filteredPostOptions(postOptions, scope.row.relatedUsers)">{{ value
              }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column v-if="columns[6].visible" label="状态" align="center" prop="status">
          <template #default="scope">
            <dict-tag :options="pm_require_status" :value="scope.row.status" />
          </template>
        </el-table-column>
        <el-table-column v-if="columns[11].visible" label="负责人" align="center" prop="owner" width="100">
          <template #default="scope">
            <el-tag v-for="([key, value]) in filteredRequireList(postOptions, scope.row.owner)" type="success">{{ value
              }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column v-if="columns[12].visible" label="截止时间" align="center" prop="endDate" width="150">
          <template #default="scope">
            <span>{{ parseTime(scope.row.endDate, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
          </template>
        </el-table-column>
        <el-table-column v-if="columns[13].visible" label="耗时" align="center" prop="costTime" width="60" />
        <el-table-column v-if="columns[7].visible" label="创建者" align="center" prop="createByName" />
        <el-table-column v-if="columns[8].visible" label="创建时间" align="center" prop="createTime" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
          </template>
        </el-table-column>
        <el-table-column v-if="columns[9].visible" label="修改者" align="center" prop="updateByName" />
        <el-table-column v-if="columns[10].visible" label="修改时间" align="center" prop="updateTime" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.updateTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="400px" class-name="small-padding fixed-width">
          <template #default="scope">
              <el-button link type="primary" icon="View" @click="handView(scope.row)"
                v-hasPermi="['pm:milestone:remove']">预览</el-button>
                <el-button link type="primary" icon="RefreshLeft" @click="taskShare(scope.row)">分享</el-button>
              <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
                v-hasPermi="['pm:require:edit']">修改</el-button>


              <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
                v-hasPermi="['pm:require:remove']">删除</el-button>


              <el-button link type="primary" icon="Refresh" @click="turnTask(scope.row)"
                v-hasPermi="['pm:require:quest']">转任务</el-button>

          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize" @pagination="getList" />
    </el-card>
    <!-- 添加或修改需求对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" append-to-body>
      <el-form ref="requireFormRef" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="标题" prop="title">
              <el-input v-model="form.title" placeholder="请输入标题" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="需求类型" prop="requireType">
              <el-select v-model="form.requireType" placeholder="请选择需求类型" @change="handleSelectChange">
                <el-option v-for="dict in pm_require_type" :key="dict.value" :label="dict.label"
                  :value="dict.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="关联客户" v-if="showclient">
          <el-select v-model="form.tenantId" filterable placeholder="请选择">
            <el-option v-for="([key, value], index) in Object.entries(clientList)" :key="key" :label="value"
              :value="key">
            </el-option>
          </el-select>
        </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="优先级" prop="priority">
              <el-select v-model="form.priority" placeholder="请选择优先级">
                <el-option v-for="dict in pm_priorities" :key="dict.value" :label="dict.label"
                  :value="dict.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>


        <el-row>
          <el-col :span="12">
            <el-form-item label="负责人" prop="owner">
              <el-select v-model="form.owner" filterable placeholder="请选择">
                <el-option v-for="([key, value], index) in Object.entries(postOptions)" :key="key" :label="value"
                           :value="key">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="关联人员">
              <el-select v-model="form.relatedUsers" filterable multiple placeholder="请选择">
                <el-option v-for="([key, value], index) in Object.entries(postOptions)" :key="key" :label="value"
                  :value="key">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="状态">
              <el-select v-model="form.status" placeholder="请选择状态" clearable>
                <el-option v-for="dict in pm_require_status" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="截止时间" prop="endDate">
              <el-date-picker style="width: 400px;" clearable v-model="form.endDate" type="datetime"
                              value-format="YYYY-MM-DD HH:mm:ss" placeholder="请选择截止时间">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">

          </el-col>
        </el-row>
        <el-form-item label="相关图片">
          <imageUpload  v-model="form.files" />
        </el-form-item>
        <div style="color: #F56C6C; margin-left: 80px;">单个任务按标题转任务，如果想添加多个任务，请按“1.” “2.” “3.” 这种格式书写</div>


        <el-form-item label="内容">
          <editor v-model="form.content" :min-height="130" :height="1"/>
        </el-form-item>

      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>


    <!-- 预览需求需求对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.viewVisible" append-to-body>
      <el-form ref="requireFormRef" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="标题" prop="title">
              <el-input v-model="form.title" placeholder="请输入标题" readonly />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="需求类型" prop="requireType" disabled>
              <el-select v-model="form.requireType" placeholder="请选择需求类型">
                <el-option v-for="dict in pm_require_type" :key="dict.value" :label="dict.label"
                  :value="dict.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="关联客户">
              <el-select v-model="form.tenantId" filterable placeholder="请选择" disabled>
                <el-option v-for="([key, value], index) in Object.entries(clientList)" :key="key" :label="value"
                  :value="key">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态">
              <el-select v-model="form.status" placeholder="请选择状态" disabled>
                <el-option v-for="dict in pm_require_status" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="优先级" prop="priority" disabled>
              <el-select v-model="form.priority" placeholder="请选择优先级">
                <el-option v-for="dict in pm_priorities" :key="dict.value" :label="dict.label"
                  :value="dict.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="关联人员" disabled>
              <el-select v-model="form.relatedUsers" filterable multiple placeholder="请选择">
                <el-option v-for="([key, value], index) in Object.entries(postOptions)" :key="key" :label="value"
                  :value="key">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="截止时间" prop="endDate">
              <el-date-picker style="width: 400px;" clearable v-model="form.endDate" type="datetime"
                              value-format="YYYY-MM-DD HH:mm:ss" placeholder="请选择截止时间" disabled>
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12" >
            <el-form-item label="耗时" prop="costTime" >
              <el-input v-model="form.costTime" placeholder="请输入耗时"  disabled/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="创建者" prop="projectCode">
              <el-input v-model="form.createByName" placeholder="请输入创建者" readonly />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="创建时间" prop="projectCode">
              <el-input v-model="form.createTime" placeholder="请输入创建时间" readonly />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="修改者">
              <el-input v-model="form.updateByName" placeholder="修改者" readonly />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="修改时间">
              <el-input v-model="form.updateTime" placeholder="请输入创建时间" readonly />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="负责人" prop="owner">
              <el-select v-model="form.owner" filterable placeholder="请选择" disabled>
                <el-option v-for="([key, value], index) in Object.entries(postOptions)" :key="key" :label="value"
                           :value="key">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <!-- <el-form-item label="相关图片" disabled>
          <imageUpload  v-model="form.files"  />
        </el-form-item> -->
        <el-form-item label="内容">
          <div class="content" v-html="form.content" @click="showImg($event)"></div>
        </el-form-item>
      </el-form>
    </el-dialog>
    <div class="imgDolg" v-show="imgPreview.show" @click.stop="imgPreview.show = false">
      <i class="Close" id="imgDolgClose" @click.stop="imgPreview.show = false"></i>
      <img @click.stop="imgPreview.show = true" :src="imgPreview.img" style="width: 50%; height: 80%;" />
    </div>
    <!-- 转任务对话框 -->
    <el-dialog :title="dialog.title" v-model="showresolve" append-to-body width="95%">

    <PageWrapLayout>
    <div style="margin-bottom: 20px">
      <div style="display: flex; justify-content: flex-end">
        <el-radio-group v-model="radio">
          <el-radio label="top">添加到顶部</el-radio>
          <el-radio label="bottom">添加到底部</el-radio>
          <el-radio label="hide">隐藏</el-radio>
        </el-radio-group>
      </div>
      <el-divider />
      <EditableProTable
        ref="table"
        :mode="radio"
        :columns="column"
        :data="list"
        :editable-keys="editableKeys"
        @add="add"
        @on-change="onChange"
        @del="deleteAction"
      />
      <div style="margin-top: 20px">
        <el-button @click="resets">重置</el-button>
        <el-button type="primary" @click="config">提交</el-button>
      </div>
    </div>
  </PageWrapLayout>
    </el-dialog>
  </div>
</template>

<script setup name="Require" lang="ts">
import EditableProTable from '@/components/Table/EditableProTable/index.vue'
import { listRequire, getRequire, delRequire, addRequire, updateRequire } from '@/api/pm/require';
import { RequireVO, RequireQuery, RequireForm } from '@/api/pm/require/types';
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { sys_normal_disable, sys_user_sex } = toRefs<any>(proxy?.useDict('sys_normal_disable', 'sys_user_sex'));
  const { pm_priorities, pm_task_type, pm_require_status } = toRefs<any>(proxy?.useDict('pm_priorities', 'pm_task_type', 'pm_require_status'));
import api from '@/api/system/user';
const {  pm_require_type } = toRefs<any>(proxy?.useDict( 'pm_require_type'));
  const router = useRouter();
const clientList = ref([]);
const postOptions = ref([]);
const requireList = ref<RequireVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(false);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const showclient = ref(false);
const showresolve = ref(false);
const queryFormRef = ref<ElFormInstance>();
const requireFormRef = ref<ElFormInstance>();
const imgPreview = ref({
  img: '', // 存储预览图片的URL
  show: false, // 控制模态框的显示状态
});
const projectList = ref([]);
const dialog = reactive<DialogOption>({
  visible: false,
  title: '',
  viewVisible: false,
});
// 列显隐信息
const columns = ref<FieldOption[]>([
  { key: 0, label: `标题`, visible: true, children: [] },
  { key: 1, label: `需求类型`, visible: true, children: [] },
  { key: 2, label: `优先级`, visible: true, children: [] },
  { key: 3, label: `内容`, visible: false, children: [] },
  { key: 4, label: `关联客户`, visible: true, children: [] },
  { key: 5, label: `关联人员`, visible: true, children: [] },
  { key: 6, label: `状态`, visible: true, children: [] },
  { key: 7, label: `创建者`, visible: false, children: [] },
  { key: 8, label: `创建时间`, visible: false, children: [] },
  { key: 9, label: `修改者`, visible: false, children: [] },
  { key: 10, label: `修改时间`, visible: false, children: [] },
  { key: 11, label: `负责人`, visible: true, children: [] },
  { key: 12, label: `截止时间`, visible: true, children: [] },
  { key: 13, label: `耗时`, visible: true, children: [] },
]);

const initFormData: RequireForm = {
  id: undefined,
  tenantId: undefined,
  title: undefined,
  requireType: undefined,
  priority: undefined,
  content: undefined,
  files: undefined,
  relatedUsers: undefined,
  status: undefined,
  createByName: undefined,
  updateByName: undefined,
  createDeptName: undefined
}
const data = reactive<PageData<RequireForm, RequireQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 50,
    tenantId: undefined,
    title: undefined,
    requireType: undefined,
    priority: undefined,
    status: undefined,
    relatedUsers: undefined,
    params: {
    }
  },
  rules: {
    title: [
      { required: true, message: "标题不能为空", trigger: "blur" }
    ],
    requireType: [
      { required: true, message: "需求类型不能为空", trigger: "change" }
    ],
    priority: [
      { required: true, message: "优先级不能为空", trigger: "change" }
    ],
    status: [
      { required: true, message: "状态不能为空", trigger: "change" }
    ],
    owner: [
      { required: true, message: "负责人不能为空", trigger: "blur" }
    ],
  }
});
const table = ref()
const column = [
    { name: 'title', label: '任务标题', width: 160 },
    {
      name: 'projectId',
      label: '项目',
      options: [
        {
          value: -1,
          label: '全部',
        },
        {
          value: 1,
          label: '未解决',
        },
        {
          value: 0,
          label: '已解决',
        },
      ],
      valueType: 'select',
    },
    {
      name: 'requireId',
      label: '需求',
      options: [
        {
          value: -1,
          label: '全部',
        },
        {
          value: 1,
          label: '未解决',
        },
        {
          value: 0,
          label: '已解决',
        },
      ],
      valueType: 'select',
    },

    {
      name: 'milestoneId',
      label: '里程碑',
      options: [
        {
          value: -1,
          label: '全部',
        },
        {
          value: 1,
          label: '未解决',
        },
        {
          value: 0,
          label: '已解决',
        },
      ],
      valueType: 'select',
    },

    {
      name: 'taskType',
      label: '任务类型',
      options: pm_task_type.value,
      valueType: 'select',
    },
    {
      name: 'priority',
      label: '优先级',
      options: [
        {
          value: -1,
          label: '全部',
        },
        {
          value: 1,
          label: '未解决',
        },
        {
          value: 0,
          label: '已解决',
        },
      ],
      valueType: 'select',
    },
    {
      name: 'owner',
      label: '负责人',
      options: [
        {
          value: -1,
          label: '全部',
        },
        {
          value: 1,
          label: '未解决',
        },
        {
          value: 0,
          label: '已解决',
        },
      ],
      valueType: 'select',
    },

    {
      name: 'startDate',
      label: '开始时间',
      valueType: 'date',
    },
    {
      name: 'status',
      label: '状态',
      options: [
        {
          value: "待处理" ,
          label: "待处理" ,
        },
        {
          value: "处理中",
          label: "处理中",
        },
        {
          value: "已关闭",
          label: "已关闭",
        },
        {
          value: "已删除" ,
          label: "已删除" ,
        },
        {
          value: "非需求",
          label: "非需求",
        },
        {
          value: "重复",
          label: "重复",
        },
      ],
      valueType: 'select',
    },
    {
      name: 'content',
      label: '内容',
      valueType: 'input',
    },
  ]

  let datas = [ ]

  let arrKeys = datas.map((item) => item.id).filter((item) => ![6247418504, 6246921229].includes(item))
  const radio = ref('bottom')
  const list = ref(datas)
  let editableKeys = ref(arrKeys)
  const dataSource = ref(datas)
  const deleteAction = (row) => {
    console.log('删除', row)
    ElMessage.success('点击删除')
  }
  const onChange = (val) => {
    dataSource.value = val
  }
  const add = () => {}

  // 重置
  const resets = () => {
    ElMessage.success('重置成功')
    table.value.reset()
  }
  const config = () => {
    list.value = dataSource.value
    console.log('点击提交=========', dataSource.value)
    ElMessage.success('点击提交数据')
  }

const { queryParams, form, rules } = toRefs(data);


const showImg = (e) => {
  if (e.target.tagName === 'IMG' && e.target.src) {
    imgPreview.value.img = e.target.src; // 更新预览图片的URL
    imgPreview.value.show = true; // 显示模态框
  }
};

/** 分享按钮操作 */
const taskShare = async (row?: RequireVO) => {
  reset();
  const _id = row?.id || ids.value[0]
  router.push({ path: `/pm/require-share/index/${_id}` });
}

const handleSelectChange = () => {
  showclient.value = form.value.requireType === 'customer';
  if (form.value.requireType === 'inner') {
    form.value.tenantId = ''
  }
};

/** 查询需求列表 */
const getList = async () => {
  loading.value = true;
  queryParams.value.isAsc = 'desc';
  queryParams.value.orderByColumn = 'id';
  const res = await listRequire(queryParams.value);
  requireList.value = res.rows;
  total.value = res.total;
  loading.value = false;
}

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
}

/** 表单重置 */
const reset = () => {
  form.value = { ...initFormData };
  requireFormRef.value?.resetFields();
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
}

/** 多选框选中数据 */
const handleSelectionChange = (selection: RequireVO[]) => {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
const handleAdd = async () => {
  reset();

  dialog.visible = true;
  dialog.title = "添加需求";
  form.value.requireType = "inner";
  form.value.priority = "middle";
  form.value.status = "processing";
  showclient.value = false;
}

/** 修改按钮操作 */
const handleUpdate = async (row?: RequireVO) => {
  reset();
  // if (form.value.requireType === 'inner') {
  //   showclient.value = false;
  // } else {
  //   showclient.value = true;
  // }
  const _id = row?.id || ids.value[0]
  const res = await getRequire(_id);
  res.data.relatedUsers = JSON.parse(res.data.relatedUsers);
  if(res.data.requireType ==="inner") {
    showclient.value = false;
  } else {
    showclient.value = true;
  }
  Object.assign(form.value, res.data);
  dialog.visible = true;
  dialog.title = "修改需求";
}

/** 预览按钮操作 */
const handView = async (row?: RequireVO) => {
  reset();
  const _id = row?.id || ids.value[0]
  const res = await getRequire(_id);
  res.data.relatedUsers = JSON.parse(res.data.relatedUsers);
  Object.assign(form.value, res.data);
  dialog.viewVisible = true;
  dialog.title = "预览需求";
}

/** 提交按钮 */
const submitForm = () => {
  requireFormRef.value?.validate(async (valid: boolean) => {

    if (valid) {
      buttonLoading.value = true;
      form.value.relatedUsers = JSON.stringify(form.value.relatedUsers);
      if (form.value.id) {
        await updateRequire(form.value).finally(() => buttonLoading.value = false);
      } else {
        await addRequire(form.value).finally(() => buttonLoading.value = false);
      }
      proxy?.$modal.msgSuccess("操作成功");
      dialog.visible = false;
      await getList();
    }
  });
}

/** 删除按钮操作 */
const handleDelete = async (row?: RequireVO) => {
  const _ids = row?.id || ids.value;
  await proxy?.$modal.confirm('是否确认删除需求编号为"' + _ids + '"的数据项？').finally(() => loading.value = false);
  await delRequire(_ids);
  proxy?.$modal.msgSuccess("删除成功");
  await getList();
}

/** 转任务按钮操作 */
const turnTask = async (row?: RequireVO) => {
  dialog.title = "生成任务";
  showresolve.value = true;
}



/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download('pm/require/export', {
    ...queryParams.value
  }, `require_${new Date().getTime()}.xlsx`)
};

/** 加载下拉列表数据 */
const getSelectList = async () => {
  const data1 = await api.affiliatePperson('user');
  postOptions.value = data1.data;
  const data2 = await api.affiliatePperson('tenant');
  clientList.value = data2.data;
  const data3 = await api.affiliatePperson('project');
  projectList.value = data1.data;
};

const filteredRequireList = (data, param: string | number) => {
  return Object.entries(data).filter(([key]) => key === param);
};

const filteredPostOptions = (data, param: string) => {
  let parsed = JSON.parse(param);
  parsed = Array.isArray(parsed) ? parsed : [];
  return Object.entries(data).filter(([key]) => parsed.includes(key));
};

onMounted(() => {
  getList();
  getSelectList();
});

</script>
<style scoped>
:deep(img) {
  /* 样式内容 */
  width: 100px;
  height: 100px;
}
:deep(.ql-editor li) {
  display: flex;
  align-items: center; /* 水平居中（如果需要） */
  /* 样式内容 */
 width: 100%;
}
:deep(.ql-editor p) {
  display: flex;
  align-items: center; /* 水平居中（如果需要） */
  /* 样式内容 */
 width: 100%;
}

:deep(.ql-align-center) {
  display: flex;
  align-items: center; /* 水平居中（如果需要） */
  /* 样式内容 */
 width: 100%;
}

:deep(.content p) {
  display: flex;
  align-items: center; /* 水平居中（如果需要） */
  /* 样式内容 */
 width: 100%;
}

:deep(.content li) {
  display: flex;
  align-items: center; /* 水平居中（如果需要） */
  /* 样式内容 */
 width: 100%;
}

.content {
  border: 1px solid #d3d3d3;
  width: 100%;
}

.content img {
  max-width: 20%;
  margin-right: 5px;
  margin-left: 5px;
}

.content .ql-syntax {
  white-space: pre-line;
  word-wrap: break-word;
  /* 允许在适当的位置换行 */
  overflow-wrap: break-word;
}

.imgDolg {
  width: 100vw;
  height: 100vh;
  position: fixed;
  z-index: 9999;
  background-color: rgba(0, 0, 0, 0.8);
  top: 0;
  left: 0;
  display: flex;
  align-items: center;
  justify-content: center;
}

#imgDolgClose {
  position: fixed;
  top: 25px;
  cursor: pointer;
  right: 4%;
  font-size: 50px;
  color: white;
}
</style>
